@rbxts/jsnatives
Proxy - set hook
The set
hook is triggered when a property is set on the proxy.
Signature
function set<T>(target: T, key: unknown, value: unknown, proxy: T): boolean;
Description
The set
handler trap is called when a property is set on the proxy object. It allows you to intercept and customize property assignment operations.
Parameters
target
: The original target object the proxy is wrappingkey
: The property key (string, number, or symbol) being setvalue
: The new value being assigned to the propertyproxy
: The proxy instance itself
Return value
- A boolean indicating whether the assignment succeeded. Return
true
to indicate success, orfalse
to indicate failure (which will trigger an error).
Examples
Basic property assignment interception
const target = {};const proxy = new Proxy(target, { set: (target, prop, value, proxy) => { console.log(`Setting property ${String(prop)} to ${value}`); target[prop] = value; return true; // Indicate success }});
proxy.name = "John"; // Logs: "Setting property name to John"console.log(target.name); // "John" (the change is reflected in the target)
Validation
const numbers = [];const proxy = new Proxy(numbers, { set: (target, prop, value, proxy) => { // Ensure we're only adding numbers to the array if (typeIs(value, "number")) { target[prop] = value; return true; } console.error("Only numbers can be added to this array"); return false; // Reject the operation }});
proxy.push(1); // Worksproxy.push(2); // Works// proxy.push("3"); // Logs: "Only numbers can be added to this array" and fails with error "[PROXYERROR] Failed to set value on target object"console.log(numbers); // [1, 2]
Transformation
const target = {};const proxy = new Proxy(target, { set: (target, prop, value, proxy) => { // Convert all string values to uppercase if (typeof value === "string") { target[prop] = value.toUpperCase(); } else { target[prop] = value; } return true; }});
proxy.name = "john";proxy.age = 30;console.log(target); // { name: "JOHN", age: 30 }
Using raw properties to bypass the set trap
const target = {};const raw = { directProp: "unchanged" };const proxy = new Proxy(target, { set: (target, prop, value, proxy) => { console.log(`Set trap for ${String(prop)}`); target[prop] = `Modified: ${value}`; return true; }}, raw);
proxy.normalProp = "value"; // Logs: "Set trap for normalProp"proxy.directProp = "changed"; // Doesn't trigger the set trapconsole.log(proxy.normalProp); // "Modified: value" (went through set trap)console.log(proxy.directProp); // "changed" (raw property was modified directly)